package com.franzliszt.OrderOnline.sunzhengyi.LoginPackage;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;


import com.franzliszt.OrderOnline.SQLite.Dao;
import com.franzliszt.OrderOnline.tool.Goods;
import com.franzliszt.OrderOnline.tool.GoodsList;
import com.franzliszt.OrderOnline.util.KillProcess;
import com.franzliszt.OrderOnline.util.SP;
import com.franzliszt.hospitalnumberingsystem.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

//import cn.smssdk.EventHandler;
//import cn.smssdk.SMSSDK;

public class RegisterADDForget extends AppCompatActivity {
    private List<View> views = new ArrayList<>(  );
    private List<String> Title = new ArrayList<>(  );
    private TabLayout TotalTitle;
    private ViewPager viewPager;
    private EditText RegisterUser,RegisterPassWord,RegisterPhoneNumber,ForgetPhone,ForgetNewPass1,ForgetNewPass2;
    private Button RegisterSex,SubmitRegister,SubmitForget;
    private TextView ErrorString,Other;
    private ImageView RegisterAndForgetGoBack;
    private String GetID,GetIDFromAccount,GetPassWordFromAccount;
    private static boolean Flag = true;
    //EventHandler eventHandler;
    private Toast ErrorTips;
    private int Current;
    public static final String TAG = "RegisterADDForget";
    private Dao dao;
    private List<GoodsList> goodsArrayList = new ArrayList<>();
    //private List<Payment> paymentList;
    //private com.franzliszt.hospitalnumberingsystem.util.SP sp;
    private SP sp;
    private KillProcess killProcess;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_register_addforget);
        /*********建表关键句*************/
        InitView();
        InitAdapter();
        //Listener();
//        Handler handler = new Handler(  ){
//            @Override
//            public void handleMessage(@NonNull Message msg) {
//                super.handleMessage( msg );
//                if (GetVerificationCode != null){
//                    if (Current > 0){
//                        Current--;
//                        GetVerificationCode.setEnabled( false );
//                        GetVerificationCode.setText( "获取验证码" +"("+Current+"s)");
//                        sendEmptyMessageDelayed( 0,1000 );
//                    }else {
//                        GetVerificationCode.setEnabled( true );
//                        GetVerificationCode.setText( "获取验证码" );
//                    }
//                }
//            }
//        };
//        eventHandler = new EventHandler(){
//            @Override
//            public void afterEvent(final int i, int i1, Object o) {
//                if (i == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//                    //提交短信、语音验证码成功
//                    runOnUiThread( ()->{
//                        if (i1 == SMSSDK.RESULT_COMPLETE) {
//                            AlertDialog.Builder builder = new AlertDialog.Builder( RegisterADDForget.this );
//                            builder.setTitle( "提示" )
//                                    .setMessage( "注册成功" )
//                                    .setIcon( R.drawable.success )
//                                    .setCancelable( true )
//                                    .create()
//                                    .show();
//                            Flag = true;
//                        }else {
//                            AlertDialog.Builder builder = new AlertDialog.Builder( RegisterADDForget.this );
//                            builder.setTitle( "提示" )
//                                    .setMessage( "验证码不正确" )
//                                    .setIcon( R.drawable.smssdk_sign )
//                                    .setCancelable( true )
//                                    .create()
//                                    .show();
//                            Flag = false;
//                        }
//                    } );
//                } else if (i == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//                    //获取短信验证码成功
//                    runOnUiThread( ()->{
//                        Current = 60;
//                        handler.sendEmptyMessage( 0 );
//                        boolean smart = (Boolean) o;
//                        if (smart) {
//                            //通过Mob云验证
//                            Toast.makeText( RegisterADDForget.this, "通过Mob云验证", Toast.LENGTH_SHORT ).show();
//                        } else {
//                            Toast.makeText( RegisterADDForget.this, "验证码获取成功", Toast.LENGTH_SHORT ).show();
//                            //依然走短信验证
//                        }
//                    } );
//                } else if (i1 == SMSSDK.RESULT_ERROR) {
//                    Toast.makeText( RegisterADDForget.this, "验证码获取失败", Toast.LENGTH_SHORT ).show();
//                    //失败回调
//                } else {
//                    //其他失败回调
//                    ((Throwable) o).printStackTrace();
//                }
//            }
//
//        };
//        SMSSDK.registerEventHandler( eventHandler );
        /***************注册和找回密码界面GoBack键******************/
//        RegisterAndForgetGoBack.setOnClickListener( new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent( RegisterADDForget.this,Login.class );
//                startActivity( intent );
//            }
//        } );
//    }
    }
    /********************初始化主界面控件**********************/
    private void InitView() {
        TotalTitle = findViewById( R.id.TotalTitle );
        viewPager = findViewById( R.id.ViewPager );
        Other = findViewById(R.id.exchangeFunc);
        Other.setVisibility(View.GONE);
        dao = new Dao(RegisterADDForget.this);
        sp = SP.getInstance();
        killProcess = KillProcess.getInstance();
        killProcess.addActivity(RegisterADDForget.this);
    }
    private void InitAdapter(){
        /********************注册子界面***********************/
       View viewRegister = LayoutInflater.from( RegisterADDForget.this ).inflate( R.layout.register_item,null );
        RegisterUser = viewRegister.findViewById( R.id.Register_User );
        RegisterPassWord = viewRegister.findViewById( R.id.Register_PassWord);
        RegisterSex = viewRegister.findViewById( R.id.Register_Sex );
        RegisterPhoneNumber = viewRegister.findViewById( R.id.Register_PhoneNumber );
        SubmitRegister = viewRegister.findViewById( R.id.SubmitRegister );
        //RegisterVerificationCode = viewRegister.findViewById( R.id.Register_Code );
        //GetVerificationCode = viewRegister.findViewById( R.id.GetVerificationCode );
        /********************找回密码子界面***********************/
       View viewForget = LayoutInflater.from( RegisterADDForget.this ).inflate( R.layout.forget_item,null );
       ForgetPhone = viewForget.findViewById( R.id.Forget_Phone );
       ForgetNewPass1 = viewForget.findViewById(R.id.Forget_NewPass_1);
       ForgetNewPass2 = viewForget.findViewById(R.id.Forget_NewPass_2);
       SubmitForget = viewForget.findViewById( R.id.SubmitForget );
        /********************获取验证码***********************/
//        GetVerificationCode.setOnClickListener( new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                String PhoneNumber = RegisterPhoneNumber.getText().toString();
//                if ((!JudgePhoneNumberFormat( PhoneNumber )) && (!JudgePhoneNumberLength( PhoneNumber ) )){
//                    Toast.makeText( RegisterADDForget.this,"手机号码格式错误",Toast.LENGTH_SHORT ).show();
//                    return;
//                }
//                //SMSSDK.getVerificationCode( "86",PhoneNumber );
//            }
//        } );
        /********************添加标题，绑定ViewPager***********************/
       views.add( viewRegister );
       views.add( viewForget );
       Title.add( "注册账号" );
       Title.add( "忘记密码" );
       RegisterAddForgetAdapter adapter = new RegisterAddForgetAdapter( views,Title );
       for (String title : Title){
           TotalTitle.addTab( TotalTitle.newTab().setText( title ) );
       }
       TotalTitle.setupWithViewPager( viewPager );
       viewPager.setAdapter( adapter );
        /********************选择性别监听事件**********************/
        RegisterSex.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SexChoose();
            }
        } );
        /********************注册监听事件**********************/
        SubmitRegister.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            boolean result = Information();
            if (result) {
                /**register success*/
                //String PhoneNumber = RegisterPhoneNumber.getText().toString().trim();
                //String Code = RegisterVerificationCode.getText().toString().trim();
                //SMSSDK.submitVerificationCode( "86", PhoneNumber,Code);
                //submitVerificationCode("86", PhoneNumber,Code);
                processError("注册成功");
            }
        }
    } );
        /********************找回密码事件***********************/
       SubmitForget.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EnterPassWord();
            }
        } );
}
    private void EnterPassWord(){
        int code = 0;
        boolean flag = false;
        goodsArrayList = dao.QueryAll();
        String UserName = ForgetPhone.getText().toString().trim();
        String PassWord1 = ForgetNewPass1.getText().toString().trim();
        String PassWord2 = ForgetNewPass2.getText().toString().trim();
        //String User = null;
        if (goodsArrayList != null) {
            for (int i = 0; i < goodsArrayList.size(); i++) {
                if (UserName.equals(goodsArrayList.get(i).getUserName())) {
                    if (goodsArrayList.get(i).getPassWord().equals(PassWord1))
                    {
                        code = 4;
                    }else {
                        flag = true;
                       // User = informationList.get(i).getUserName();
                        //PayPassWord = informationList.get(i).getPayPass().trim();
                    }
                    break;
                }
            }
        }else {
            code = 2;
        }
        if (PassWord1.equals(PassWord2) && flag){
            code = 1;
            flag = false;
        }
        //Toast.makeText(RegisterADDForget.this,code+"",Toast.LENGTH_LONG).show();
        if (PassWord1.equals(PassWord2) && code != 1 && code != 4) code = 5;
        if (!PassWord1.equals(PassWord2))code = 3;

        switch (code){
            case 1:
                //sp.PutData(RegisterADDForget.this,"",User);
                sp.PutData(RegisterADDForget.this,"PassWord",PassWord1);
                sp.PutData(RegisterADDForget.this,"User",UserName);
                //sp.PutData(RegisterADDForget.this,"PayPassWord",PayPassWord);
                startActivity(new Intent(RegisterADDForget.this,UpdatePasswordActivity.class));
                break;
            case 2:
                processError("尚未注册任何账号");
                break;
            case 3:
                processError("两次密码不一致");
                break;
            case 4:
                processError("与原密码一致，无需修改");
                break;
            case 5:
                processError("该手机号码尚未绑定任何账号");
                break;
        }
    }
    public static void submitVerificationCode(String Country,String Phone,String Code){
        //SMSSDK.submitVerificationCode( Country, Phone,Code);
    }
    /********************选择性别AlertDialog事件**********************/
    private void SexChoose(){
        final AlertDialog.Builder builder = new AlertDialog.Builder( RegisterADDForget.this );
        builder.setTitle("请选择您的性别");
        builder.setIcon(R.drawable.icon_sex);
        final String[] items = {"男","女","中性"};
        builder.setSingleChoiceItems( items,0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String Sex = items[which];
                RegisterSex.setText(Sex);
                RegisterSex.setTextColor(getResources().getColor(R.color.colorBlack));
            }
        } );
        builder.show();
    }
    /********************将用户填写的数据保存至数据库**********************/
    private boolean Information(){
        goodsArrayList = dao.QueryAll();
        //Toast.makeText(RegisterADDForget.this,informationList.size()+"",Toast.LENGTH_LONG).show();
        String Name = RegisterUser.getText().toString();
        String PassWord = RegisterPassWord.getText().toString();
        String PhoneNumber = RegisterPhoneNumber.getText().toString().trim();
        String Sex = RegisterSex.getText().toString();
        if (TextUtils.isEmpty( Name )){
            processError("用户名不能为空");
            RegisterUser.setText("");
            return false;
        }
        if (TextUtils.isEmpty( PassWord )){
            processError("密码不能为空");
            RegisterPassWord.setText("");
            return false;
        }
        if (TextUtils.isEmpty( PhoneNumber )){
            processError("手机号码不能为空");
            RegisterPhoneNumber.setText("");
            return false;
        }
        if (TextUtils.isEmpty( Sex )){
            processError("性别不能为空");
            RegisterSex.setText("请选择您的性别");
            return false;
        }
        if (PassWord.length() < 6 && PassWord.length() > 12){
            processError("密码只能在6-12位");
            RegisterPassWord.setText("");
            return false;
        }
        if (!JudgePhoneNumberLength(PhoneNumber)){
            processError("手机号码只能为11位");
            RegisterPhoneNumber.setText( "" );
            return false;
        }
        if (JudgePhoneNumberFormat(PhoneNumber)) {
            processError("手机号码格式错误");
            RegisterPhoneNumber.setText( "" );
            return false;
        }
        if (goodsArrayList != null ){
            for (int i = 0; i < goodsArrayList.size(); i++) {
                if (Name.equals(goodsArrayList.get(i).getUserName())){
                    //如果账号已存在
                    processError("账号已经存在");
                    return false;
                }
            }
        }
        dao.Insert(new GoodsList(Name,PassWord,0,"0",0.0f,0,0,0));
        return true;
    }

//    private void processError(Object data) {
//        int status = 0;
//        // 根据服务器返回的网络错误，给toast提示
//        try {
//            ((Throwable) data).printStackTrace();
//            Throwable throwable = (Throwable) data;
//
//            JSONObject object = new JSONObject(
//                    throwable.getMessage());
//            String des = object.optString("detail");
//            status = object.optInt("status");
//            if (!TextUtils.isEmpty(des)) {
//                //showErrorToast(des);
//                Toast.makeText( RegisterADDForget.this,"des",Toast.LENGTH_SHORT ).show();
//                return;
//            }
//        } catch (Exception e) {
//            Log.w(TAG, "", e);
//        }
//    }
    public void Exit(View view){
        startActivity(new Intent(RegisterADDForget.this,Login.class));
    }
    private void processError(String errorCode){
        ErrorTips = new Toast(RegisterADDForget.this);
        View view = LayoutInflater.from( RegisterADDForget.this ).inflate( R.layout.passworderror,null,false );
        ErrorString = view.findViewById(R.id.ErrorTips);
        ErrorString.setText(errorCode);
        ErrorTips.setView( view );
        ErrorTips.setGravity( Gravity.CENTER,0,0 );
        ErrorTips.show();
    }

    public boolean JudgePhoneNumberLength(String Number){
        if (TextUtils.isEmpty( Number )){
            return false;
        }else {
            return Number.length() == 11 ? true : false;
        }
    }
    /*一、中国电信号段：
133、153、173、177、180、181、189、191、199
二、中国联通号段:
130、131、132、155、156、166、175、176、185、186
三、中国移动号段:
134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188、198*/
    private  boolean JudgePhoneNumberFormat(String Number){
        //第一位必须为1，第二位为345789其中一位，后面九位从0-9都可以
        String NumberFormat = "[1][345789]\\d[9]";
        if (TextUtils.isEmpty( Number )){
            return false;
        }else {
            return Number.matches( NumberFormat );
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //SMSSDK.unregisterEventHandler( eventHandler );
    }
}

